# For a given email template, sends emails to active contacts who have not been
# sent that email yet.
#
# author: matias
# 
# TODO(matias): make type-of-email agnostic, once Newsletter has a superclass.

class MassEmailSender
  attr_reader :newsletter
  attr_reader :contacts
  attr_reader :success_count
  attr_reader :error_count
  attr_reader :skipped_count

  def initialize(newsletter, pause=false)
    raise ArgumentError, "Newsletter is still a draft" if newsletter.draft
    @newsletter = newsletter
    @pause = pause
  end
  
  def get_contacts!
    @contacts = Contact.find(:all, :conditions => ["active = ?", true])
  end
  
  def send_emails!
    raise ArgumentError, "No contacts found" if not @contacts or @contacts.empty?
    @success_count = @error_count = @skipped_count = 0
    
    @contacts.each do |contact|
      begin
        yield "#{contact.email}... "
        sent_email = SentEmail.find_by_contact_id_and_newsletter_id(
            contact.id, @newsletter.id)
        if sent_email.nil?
          MassEmail.deliver_newsletter(contact, @newsletter)
          yield "ok"
          @success_count += 1
        else
          yield "already sent!"
          @skipped_count += 1
        end
      rescue
        yield "error: #{$!}"
        @error_count += 1
      ensure
        yield "\n"
        sleep 0.75 if @pause
      end
    end
  end  
end
